//
//  ViewController.m
//  testWebsocketLbl
//
//  Created by huge on 16/4/14.
//  Copyright © 2016年 huge. All rights reserved.
//

#import "ViewController.h"
#import "SRWebSocket.h"

@interface ViewController () <SRWebSocketDelegate, UITextViewDelegate>

@end

@implementation ViewController
{
    SRWebSocket *_webSocket;

}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewWillAppear:(BOOL)animated
{
    
    [super viewWillAppear:animated];
    [self reconnect:nil];

}
- (void)viewDidAppear:(BOOL)animated{

    [super viewDidAppear:animated];
    
}

- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
    
    _webSocket.delegate = nil;
    [_webSocket close];
    _webSocket = nil;
    
}

#pragma mark network connect

- (IBAction)reconnect:(id)sender
{
    _webSocket.delegate = nil;
    [_webSocket close];
    _webSocket = [[SRWebSocket alloc] initWithURLRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"ws://192.168.4.227:2016"]]];
    _webSocket.delegate = self;
    
    self.testWebsocketLbl.text = @"Opening Connection...";
    [_webSocket open];

}

- (IBAction)closeWebsocket:(id)sender
{
    _webSocket.delegate = nil;
    [_webSocket close];
    _webSocket = nil;
    
    self.testWebsocketLbl.text = @"closed...";
    NSLog(@"closed");
}

#pragma mark  -- message handle

- (IBAction)sendPing:(id)sender
{
    NSLog(@" readyState :%ld",(long)_webSocket.readyState);
    NSLog(@"ping");

    [_webSocket sendPing:nil];
}

-(IBAction)sendData:(id)sender
{
    NSLog(@" readyState :%ld",(long)_webSocket.readyState);
    
    NSString* Message = @"hello chongge";
    NSLog(@"%@",Message);
    
    [_webSocket send: Message];

}


#pragma mark --SRwebsocket delegate

-(void)webSocketDidOpen:(SRWebSocket *)webSocket
{
    NSLog(@"websocket Connected");
    self.testWebsocketLbl.text = @"Connected";
}

-(void)webSocket:(SRWebSocket *)webSocket didFailWithError:(NSError *)error
{
    
    NSLog(@":( Websocket Failed With Error %@", error);
    
    self.testWebsocketLbl.text = @"Connection Failed! ";
    _webSocket = nil;
    
}

- (void)webSocket:(SRWebSocket *)webSocket didReceiveMessage:(id)message;
{
    NSLog(@"Received \"%@\"", message);
    
}

- (void)webSocket:(SRWebSocket *)webSocket didCloseWithCode:(NSInteger)code reason:(NSString *)reason wasClean:(BOOL)wasClean;
{
    NSLog(@"WebSocket closed");
    self.testWebsocketLbl.text = @"Connection Closed! ";
    _webSocket = nil;
}

- (void)webSocket:(SRWebSocket *)webSocket didReceivePong:(NSData *)pongPayload;
{
    NSLog(@"Websocket received pong");
}



@end
